package com.linfeng.server.oauth.exception;

import com.linfeng.component.common.exception.CustomException;
import com.linfeng.component.common.exception.CustomExceptionCode;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;


public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity<CustomException> translate(Exception e) throws Exception {

        if (e instanceof UnsupportedGrantTypeException) {
            //认证方式异常
            return ResponseEntity.ok(new CustomException(CustomExceptionCode.UNAUTHORIZED));
        } else if (e instanceof InvalidGrantException) {
            //用户名或密码错误
            return ResponseEntity.ok(new CustomException(CustomExceptionCode.USERNAME_OR_PASSWORD_ERROR));
        } else if (e instanceof InvalidTokenException) {
            // token验证失败
            return ResponseEntity.ok(new CustomException(CustomExceptionCode.TOKEN_VERIFY));
        }

        return ResponseEntity.ok(new CustomException(CustomExceptionCode.SYSTEM_EXCEPTION));
    }
}
